
import { createStore, Commit } from 'vuex';
//  引入自己封装过得 axios
import axios from '../api/request';
// 引入 axios的 AxiosRequestConfig 类型
import { AxiosRequestConfig } from 'axios';
// import { testData, testPosts,  type ColumnProps, type PostProps} from '../../testData';
// import { reqGetColumns, reqGetColumn, reqGetPosts, reqPostToken, reqGetUserInfo , reqCreatePosts, reqPosts} from '../api/request';
import { arrToObj, ObjToArr } from '../helper';

export interface UserInfo {
  isLogin?: boolean;
  nickName?: string;
  _id?: string;
  column?: string;
  email?: string;
  avatar?: ImageProps;
  description?: string;
}
// avatar类型
export interface Avatar {
  _id?: string
  url?: string
  createdAt?: string
  fitUrl?: string
}
// 专栏类型
export interface ColumnProps {
  _id: string;
  title: string;
  avatar?: ImageProps;
  description: string;

}
// 文章类型
export interface PostProps {
  _id?: string;
  title: string;
  excerpt?: string;
  content?: string;
  image?: ImageProps | string;
  createdAt?: string;
  column: string;
  author?: string | UserInfo;
  isHTML?: boolean;
}
export interface Err {
  isErr: boolean
  message?: string
}
interface ListProps<p> {
  [id: string]: p
}
// 全局的posts 类型
export interface GlobalPostsProps {
  data: ListProps<{ [_id: string]: PostProps }>
  loadedColumns: ListProps<{ column: string, total: number, currentPage: number }>
}
// 全局的 state类型
export interface GlobalDataProps {
  loading: boolean
  column: { data: ListProps<ColumnProps>, currentPage: number, total: number }
  posts: GlobalPostsProps
  user: UserInfo,
  token: string,
  err: Err
  propsDetail: PropsDetail
}
export interface PropsDetail {
  _id?: string
  title?: string
  excerpt?: string
  content?: string
  image?: ImageProps
  author?: UserInfo
  updatedAt?: string
  createdAt?: string
  isHTML?: boolean
}
// export interface Author {
//   _id?: string
//   email?: string
//   nickName?: string
//   description?: string
//   avatar?:string
//   column?:string
// }
export interface ResponseType<T = {}> {
  code: number
  msg: string
  data: T
}
export interface ImageProps {
  _id?: string;
  url?: string;
  createdAt?: string;
  fitUrl?: string;
}
// const reqAndCommit = async (func: Function, commit: Commit, mutationName: string, id?: string, info?: { email: string, password: string }) => {
//   const { data } = await func(id, info)
//   commit(mutationName, data)
//   return data
// }
// cofing 配置项
const asyncAndCommit = async (url: string, cofing: AxiosRequestConfig, commit?: Commit, mutationName?: string, extraData?: string) => {
  try {
    const { data, status } = await axios(url, cofing)
    if (status === 200) {
      if (commit && mutationName) {
        if (extraData) {
          commit(mutationName, { data, extraData })
        } else {
          commit(mutationName, data)
        }
      }
      return data
    }
    //  else {
    //   return Promise.reject('err')
    // }
  } catch (error) {
    // console.log('stort 121', error);
    return Promise.reject(error)
  }
  // axios(url, cofing).then(res => {
  //   if (res.status === 200) {
  //     if (commit && mutationName) {
  //       commit(mutationName, res.data)
  //     }
  //     return res.data

  //   }else {
  //     return Promise.reject('err')
  //   }
  // }).catch(err => Promise.reject(err))
}
const store = createStore<GlobalDataProps>({
  state: {
    // 加载
    loading: false,
    // 专栏列表
    column: { data: {}, currentPage: 0, total: 0 },
    // 文章列表
    posts: { data: {}, loadedColumns: {} },
    user: { isLogin: false },
    token: localStorage.getItem('toKen') ?? '',
    // 错误
    err: { isErr: false },
    propsDetail: {}
  },
  mutations: {
    // 登陆
    login(state) {
      state.user = { ...state.user, isLogin: true, nickName: 'dc' }
    },
    // 添加专栏
    GETCOLUMNS(state, columns) {
      // 合并
      // state.column.data = { ...state.column.data , ...arrToObj(columns.data.list)}
      // state.column.isLoaded = true
      const { data } = state.column  // 把当前column data 解构出来
      
      const { list, count, currentPage } = columns.data  // list 返回数据，而count 总得条数
      state.column = {
        // 合并对象
        data: { ...data, ...arrToObj(list) },
        total: count,
        currentPage: currentPage
      }

    },
    // 获取专栏详细
    GETCOULUMN(state, data) {
      state.column.data[data.data._id] = data.data
      // console.log(data.data);

    },
    // 获取专栏id 的文章列表
    GETPOSTS(state, { data, extraData }) {
      state.posts.data[extraData] = { ...state.posts.data[extraData], ...arrToObj(data.data.list) }
      state.posts.loadedColumns[extraData] = { column: extraData, total: data.data.count, currentPage: data.data.currentPage }
    },
    // 设置loading
    SETLOADING(state, boolean) {
      state.loading = boolean
    },
    // 设置 toKen
    SETTOKEN(state, data) {
      state.token = data.data.token
      localStorage.setItem('toKen', data.data.token)
      axios.defaults.headers.common.Authorization = `Bearer ${store.state.token}`
    },
    // 登陆成功更新用户信息
    UPADTEUSERINFO(state, info) {
      const { data } = info
      state.user = { isLogin: true, ...data }

    },
    // 退出登陆
    OUTLOGIN(state) {
      state.user = { isLogin: false }
      state.token = ''
      // 清空这个请求头
      delete axios.defaults.headers.common.Authorization
      // 清除本地token
      localStorage.removeItem('toKen')
    },
    SETERR(state, e: Err) {
      state.err = e
    },
    // 获取单个文章
    GETPOSTDETAIL(state, { data }) {
      // if (state.posts.data[data.column] &&state.posts.data[data.column][data._id] ) {
      // state.posts.data[data.column] ? state.posts.data[data.column] = state.posts.data[data.column] : state.posts.data[data.column] = {}
      if (!state.posts.data[data.column]) {
        state.posts.data[data.column] = {}
      }
      state.posts.data[data.column][data._id] = data
      // }
    },
    // 更新文章数据
    UPDATEPOSTS(state, { data }) {
      // 如果返回的数据跟本地文章列表数据id相同  就会替换掉
      // console.log(state.posts.data[data.column][data._id]._id , data._id );
      // const { _id, column } = data
      // state.posts.data[data.column][data._id] = data

      if (!state.posts.data[data.column]) {
        state.posts.data[data.column] = {}
      }
      state.posts.data[data.column][data._id] = data
    },
    // 删除文章
    DELPOSTS(state, { data }) {
      setTimeout(() => {
        delete state.posts.data[data.column][data._id]
      }, 2000);
    },
    // 创建文章
    CREATEPOSTS(state, { data }) {
      // state.posts.data[data.column][data._id] = data
      if (!state.posts.data[data.column]) {
        state.posts.data[data.column] = {}
      }
      state.posts.data[data.column][data._id] = data

    }
  },


  actions: {
    // 获取专栏列表  如果不传params 就是默认{} 
    getColumns({ state, commit }, params = {}) {
      // 如果没有 就使用默认值
      const { currentPage = 1, pageSize = 6 } = params
      // /api/columns?currentPage={page}&pageSize={size} 获取专栏列表
      // if (!state.column.isLoaded) {  // 如果已经获取过就不发送请求
      //   return asyncAndCommit('/api/columns', { method: 'get' }, commit, 'GETCOLUMNS')
      // }
      // 如果当前页数 小于 传进来页数
      if (state.column.currentPage < currentPage) {
        return asyncAndCommit(`/api/columns?currentPage=${currentPage}&pageSize=${pageSize}`, { method: 'get' }, commit, 'GETCOLUMNS')
      }
    },
    // 获取专栏详细
    getColumn({ state, commit }, id: string) {
      // /api/columns/{id} 获取专栏详细
      if (!state.column.data[id]) {  // 如果存在就不发送请求
        return asyncAndCommit(`/api/columns/${id}`, { method: 'get' }, commit, 'GETCOULUMN')
      }
      // commit('GETCOULUMN', data.data)
    },
    // 获取专栏文章详细下的文章列表
    getPosts({ getters, commit }, params) {
      // /api/columns/{id}/posts?currentPage={page}&pageSize={size}  获取专栏文章
      // console.log(params.currentPage, getters.getCurrentPage(params.id));
      // const current = getters.getCurrentPage(params.id)  ? 2 :getters.getCurrentPage(params.id)
      // console.log(current);
      
      // 如果当前要发送请求的页数， 不等于所保存的当且页就不发送请求， 等于之后在发送
      if (params.currentPage !== getters.getCurrentPage(params.id)) {
        return asyncAndCommit(`/api/columns/${params.id}/posts?currentPage=${params.currentPage}&pageSize=${params.pageSize}`, { method: 'get' }, commit, 'GETPOSTS', params.id)
      }

    },
    // 获取登录信息
    getInfo({ commit }) {
      // /api/user/current 获取用户信息 get 要带响应头
      return asyncAndCommit(`/api/user/current`, { method: 'get' }, commit, 'UPADTEUSERINFO')
    },
    // 获取登录信息 和 登陆
    login({ commit, dispatch }, info: { email: string, password: string }) {
      // /api/user/login 登陆 post
      return asyncAndCommit('/api/user/login', { method: 'post', data: info }, commit, 'SETTOKEN').then(() => {
        return dispatch('getInfo')
      })
    },
    // 添加文章
    CreatePosts({ commit }, { payload }) {
      // 创建文章 /api/posts

      return asyncAndCommit(`/api/posts`, { method: 'POST', data: payload }, commit, 'CREATEPOSTS')
    },
    // 获取单个文章
    getPostDetail({ state, commit }, parmas) {
      // /api/posts/{id}
      // const currentPost = state.posts.data[id]
      // console.log(!currentPost.content);
      // 获取当前id的文章信息
      const currentPost = state.posts.data[parmas.column] && state.posts.data[parmas.column][parmas.id] || ''
      if (!currentPost || !currentPost.content) {
        return asyncAndCommit(`/api/posts/${parmas.id}`, { method: 'get' }, commit, "GETPOSTDETAIL")
      } else {
        return Promise.resolve({ data: currentPost })
      }
    },
    // 更新文章
    // patch 与 put 区别 path 更新所传递过去的数据， put 全部更新
    pathUpdataPosts({ commit }, { id, payload }) {
      // /api/posts/{id}
      console.log('更新文章');

      return asyncAndCommit(`/api/posts/${id}`, { method: 'PATCH', data: payload }, commit, 'UPDATEPOSTS')
    },
    delPosts({ commit }, id) {
      // /api/posts/{id} 删除文章    id 为 文章id
      return asyncAndCommit(`/api/posts/${id}`, { method: 'delete' }, commit, 'DELPOSTS')
    }
  },
  getters: {
    getColumns: (state) => ObjToArr(state.column.data),
    // 获取专栏用户id 展示页面专栏
    getColumnById: (state) => (id: string) => state.column.data[id],
    getPostsByCid: (state) => (id: string) => state.posts.data[id] && ObjToArr(state.posts.data[id]) || [],
    // 文章
    getCurrentPost: (state) => (params: { column: string, id: string }) => state.posts.data[params.column] && state.posts.data[params.column][params.id] || [],
    // 获取文章total
    getTotal: (state) => (id: string) => state.posts.loadedColumns[id] && state.posts.loadedColumns[id].total,
    // 文章id当前页
    getCurrentPage: (state) => (id: string) => state.posts.loadedColumns[id] && state.posts.loadedColumns[id].currentPage,

  }
  // 获取文章的 当前页
})

export default store